package xyz.scootaloo.oj.leetcode

import org.junit.Test
import xyz.scootaloo.common.TestDsl
import xyz.scootaloo.oj.ds.ListNode
import xyz.scootaloo.oj.ds.helper.CollectionBuilder

/**
 * @author flutterdash@qq.com
 * @since 2021/7/10 16:13
 */
class P21 : TestDsl {

    private fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
        if (l1 == null || l2 == null) {
            return if (l1 == null && l2 == null)
                null
            else
                l1 ?: l2
        }

        val head = ListNode(-1)
        var pointer = head

        var listNode1 = l1
        var listNode2 = l2

        while (listNode1 != null && listNode2 != null) {
            if (listNode1.`val` < listNode2.`val`) {
                pointer.next = listNode1
                listNode1 = listNode1.next
            } else {
                pointer.next = listNode2
                listNode2 = listNode2.next
            }
            pointer = pointer.next
        }

        if (listNode1 != null) {
            pointer.next = listNode1
        } else {
            pointer.next = listNode2
        }

        return head.next
    }

    @Test
    fun test0() {
        val node1 = CollectionBuilder.initNode(1, 2, 4)
        val node2 = CollectionBuilder.initNode(1, 3, 4)
        val head = mergeTwoLists(node1, node2)
        pause(head)
    }

}
